package com.vastcom.cms.action;

import com.vastcom.cms.model.Users;
import com.vastcom.cms.service.ManageService;
import com.vastcom.cms.to.SetPassTo;
import com.vastcom.cms.tools.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@CrossOrigin
@RestController
@PreAuthorize("hasAuthority('member')")
@RequestMapping("/member")
public class MemberAction {

    @Autowired
    private ManageService manageService;


@GetMapping("getMyUserInfo")
    @ResponseBody
    public HashMap getMyUserInfo()throws Exception{
    String userid=manageService.getCurrentUserId();
    HashMap m=new HashMap();
    if (Tools.isNullOrSpace(userid)){
        m.put("msg","error");
    }
    else {
        Users temp=manageService.getUser(userid);
        if(temp!=null){
            temp.setPass("");
            m.put("msg","ok");
            m.put("obj",temp);
        }
        else {
            m.put("msg","usererror");
        }
    }
    return m;
}

@PostMapping("setUserHead")
    @ResponseBody
    public HashMap setUserHead(@RequestBody Users users)throws Exception{
    HashMap m=new HashMap();
    try {
        String userid=manageService.getCurrentUserId();
        Users temp=manageService.getUser(userid);
        if(temp!=null){
            temp.setHeadimg(users.getHeadimg());
            manageService.saveUser(temp);
            m.put("msg","ok");
        }
        else {
            m.put("msg","usererror");
        }
    } catch (Exception e) {
        e.printStackTrace();
        m.put("msg","error");
    }
    return m;
}


    @PostMapping("setUserPass")
    @ResponseBody
    public HashMap setUserPass(@RequestBody SetPassTo setPassTo)throws Exception{
        HashMap m=new HashMap();
        try {
            String userid=manageService.getCurrentUserId();
            Users temp=manageService.getUser(userid);

            if(temp!=null){
                if(temp.getPass().equals(setPassTo.getOldpass())){
                    temp.setPass(setPassTo.getNewpass());
                    manageService.saveUser(temp);
                    m.put("msg","ok");
                }
                else {
                    m.put("msg","oldpasserror");
                }
            }
            else {
                m.put("msg","usererror");
            }


        } catch (Exception e) {
            e.printStackTrace();
            m.put("msg","error");
        }
        return m;
    }






}
